home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9263 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  66 lines

  1. Path: informix.com!news
  2. From: sankar <sankar@informix.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to copy an object?
  5. Date: Thu, 29 Feb 1996 11:12:55 -0800
  6. Organization: Informix.com
  7. Message-ID: <3135FAB7.3D05@informix.com>
  8. References: <4h05rb$su6@atlas.tncnet.com>
  9. NNTP-Posting-Host: sankar_pc.na.informix.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB1 (WinNT; I)
  14. CC: simonl@dataworks.com
  15.  
  16. Simon Lee wrote:
  17. > Hello,
  18. > I'm trying to have a member function return a duplicate copy of a
  19. > member data object.  How would I go about this?
  20. > Ie.
  21. > class x {
  22. > private:
  23. >         Y  *object_of_class_y;
  24. > public:
  25. >         Y GetY();
  26. > };
  27. > I would like GetY() to return a copy of object_of_class_y, not a pointer
  28. > to it.
  29. > Any email responses appreciated.
  30. > -Simon
  31.  
  32. Hi,
  33. The simple solution is, return the object by value.
  34. Depending on the members of Y, you can decide whether you need a copy contructor in Y
  35. or not.
  36.  
  37. Y x::GetY()
  38. {
  39.         return ( *object_of_class_y );
  40. }
  41.  
  42. This code returns a temporary copy of the object.
  43.  
  44. main()
  45. {
  46.         x Object1_of_x;
  47.  
  48.         // ........ Some code segemnt
  49.  
  50.         Y Object1_of_y = Object1_of_x.GetY();
  51.  
  52. }
  53.  
  54. The generated temporary copy will be assigned to "Object1_of_y".
  55.  
  56. Thanks
  57. Dayashankar
  58.